package com.blueseaapps;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.ImageView;
import android.widget.TextView;

import com.blueseaapps.data.QuizQuestionData;
import com.blueseaapps.data.ScoreKeeper;
import com.blueseaapps.ui.AnswerSelectionListener;
import com.blueseaapps.ui.QuizOptionsUI;

public class MainActivity extends Activity implements AnswerSelectionListener{

	private ImageView photoView;
	private TextView txtViewScore;
	private TextView txtViewQuesNum;
	private QuizOptionsUI options;
	private TextView txtViewQuestion;

	private ScoreKeeper scoreKeeper;
	private QuizQuestionData questionData;
	private static final String LOG_TAG = "MainActivity";
	private String selCategory = null;
	
	public static final String SELECTED_CATEGORY_KEY = "com.unknown.MainActivity.SelectedCategory";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		selCategory = getIntent().getStringExtra(SELECTED_CATEGORY_KEY);
		if((selCategory == null) || (selCategory.equalsIgnoreCase("All"))){
			selCategory = null;
		}
		initializeApp();

		txtViewScore = (TextView)findViewById(R.id.textView_score);
		txtViewQuesNum = (TextView)findViewById(R.id.textView_ques_num);
		updateScoreText();

		photoView = (ImageView)findViewById(R.id.imageView_photo);
		photoView.setAdjustViewBounds(true);
//		photoView.setMaxHeight(200);
//		photoView.setMaxWidth(150);
		txtViewQuestion = (TextView) findViewById(R.id.tv_question);
		
		try {
			QuestionManager.getInstance(selCategory, this);
		} catch (IOException e) {
			e.printStackTrace();
			showError();
		}
		displayNewPhoto();
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.quiz_menu, menu);
		return true;
	}

	private void initializeApp(){
		scoreKeeper = new ScoreKeeper();
		options = new QuizOptionsUI(this);
		options.setAnswerSelectedListener(this);
	}

	private void updateScoreText() {
		try {
			txtViewQuesNum.setText("Question " + (scoreKeeper.getNumOfQuestionsAttempted()+1) +" of "+ QuestionManager.getInstance(selCategory, this).getTotalQuestions());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		txtViewScore.setText("Score: "+String.valueOf(scoreKeeper.getNumOfQuestionsCorrectlyAnswered())+"/"+String.valueOf(scoreKeeper.getNumOfQuestionsAttempted()));
	}

	private void displayNewPhoto(){
		try {
			questionData = QuestionManager.getInstance(selCategory, this).getNextQuestion();
			if(questionData != null){
				String imageName = questionData.getImageFileName();
				try{
					InputStream imgStream = getAssets().open(imageName);
					Bitmap bmp = BitmapFactory.decodeStream(imgStream);
					BitmapDrawable img = new BitmapDrawable(bmp);
					photoView.setImageDrawable(img);
					options.setNewOptions(questionData.getOptionsData());
					options.setAnswer(questionData.getAnswer());
					txtViewQuestion.setText(questionData.getQuestion());
				}catch(RuntimeException re){
					Log.d(LOG_TAG,imageName);
				}
			}else{
				displayFinalResult();
				finish();
				QuestionManager.getInstance(null, this).resetQuestions();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			showError();
		}
	}

	private void displayFinalResult() {
		Intent beginIntent = new Intent(getApplicationContext(),FinalScoreActivity.class);
		beginIntent.putExtra(FinalScoreActivity.INTENT_EXTRA_SCORE, scoreKeeper);
		startActivity(beginIntent);
	}

	private void showError() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("An error occurred.")
		       .setCancelable(false)
		       .setNeutralButton("OK", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                MainActivity.this.finish();
		           }
		       });
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		return super.onCreateDialog(id);
	}

	private Drawable imageOperDrawableations(Context ctx, String url, String saveFilename) {
		try {
			InputStream is = (InputStream) this.fetch(url);
			Drawable d = Drawable.createFromStream(is, "src");
			return d;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public Object fetch(String address) throws MalformedURLException,IOException {
		URL url = new URL(address);
		Object content = url.getContent();
		return content;
	}

	@Override
	public void onAnswerSelected(String chosenAnswer) {
		final boolean res = chosenAnswer.equalsIgnoreCase(questionData.getAnswer());
		scoreKeeper.questionAnswered(res);
		if(res){
			options.correctAnswered();
		}else{
			options.incorrectAnswer();
		}		
		
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				updateScoreText();
				displayNewPhoto();
			}
		}, 1000);
		
		
	}

	private void displayIncorrectImage() {
		
	}

	private void displayCorrectImage() {
		
	}


}
